package com.kanche.bigbaby.collection;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Toast;

import com.kanche.bigbaby.R;
import com.kanche.bigbaby.collection.dialog.DatePickerFragment;
import com.kanche.bigbaby.collection.domain.Vehicle;
import com.kanche.bigbaby.collection.ui.ItemConfig;
import com.kanche.bigbaby.collection.ui.ItemDatePickerConfig;
import com.kanche.bigbaby.support.awesome.DrawableAwesome;

import org.joda.time.DateTime;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;

//import com.kkche.merchant.awesome.DrawableAwesome;
//import com.kkche.merchant.data.PreferencesUtils;
//import com.kkche.merchant.dialogs.DatePickerFragment;
//import com.kkche.merchant.domain.Vehicle;
//import com.kkche.merchant.domain.ui.ItemConfig;
//import com.kkche.merchant.domain.ui.ItemDatePickerConfig;

/**
 * Created by nealmi on 6/10/14.
 */
public class VehicleEditorStep3Activity extends BaseActivity implements AdapterView.OnItemClickListener, DatePickerFragment.OnDateSelectedListener {
    private ListView listView;
    private ItemsAdapter adapter;
    private DatePickerFragment datePickerFragment;
    private String itemKey;
    private long rowId;
    private KKCheDBHelper dbHelper;
    private Vehicle vehicle;
    private int tag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vehicle_editor_step3);
        toolbar = justFindIt(R.id.toolbar);
        toolbar.setTitle("选填信息");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        listView = (ListView) findViewById(R.id.listView);

        dbHelper = new KKCheDBHelper(this);
        rowId = getIntent().getLongExtra("rowId", 0L);
        vehicle = dbHelper.findVehicleByRowId(rowId);

        if (vehicle == null) {
            vehicle = Vehicle.NULL;
        }
        List<ItemConfig> items = initItemConfigs();


        adapter = new ItemsAdapter(items, this);

        listView.setOnItemClickListener(this);
        listView.setAdapter(adapter);
    }

    private List<ItemConfig> initItemConfigs() {
        List<ItemConfig> items = new ArrayList<ItemConfig>();
        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.drivingLicensePicture)
                .label(getString(R.string.driving_license))
                .hint(getString(R.string.driving_license_picture_hint))
                .height(60)
                .width(80)
                .value(vehicle.getSummary().getDrivingLicensePicture())
                .buildAvatarConfig());

        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.licenseNumber)
                .label(getString(R.string.license_number))
                .value(vehicle.getPrice().getBidPriceByTenGrand())
                .noMaxWidth(true)
                .value(vehicle.getSummary().getLicenseNumber())
                .buildEditTextConfig());

        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.commercialInsuranceExpireDate)
                .label(getString(R.string.commercial_insurance_expire_date_label))
                .hint(getString(R.string.hint_none))
                .value(vehicle.getVehicleDate().getCommercialInsuranceExpireDate())
                .buildDatePickerConfig());
        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.alcInsuranceExpireDate)
                .label(getString(R.string.alc_insurane_expire_date_label))
                .hint(getString(R.string.hint_none))
                .value(vehicle.getVehicleDate().getCompulsoryInsuranceExpireDate())
                .buildDatePickerConfig());
        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.manufactureDate)
                .label(getString(R.string.manufacture_date))
                .hint(getString(R.string.hint_none))
                .value(vehicle.getVehicleDate().getManufactureDate())
                .buildDatePickerConfig());
        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.bidPrice)
                .label(getString(R.string.bid_price_label))
                .hint(getString(R.string.bid_price_input_hint))
                .caption(getString(R.string.bid_price_caption))
                .inputFilters(new InputFilter[]{new InputFilter.LengthFilter(6)})
                .inputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL).value(vehicle.getPrice().getBidPriceByTenGrand())
                .buildEditTextConfig());


        List<Map<String, String>> transfers = CollectionUtils.toMapList(getResources().getStringArray(R.array.transfer_count_keys),
                getResources().getStringArray(R.array.transfer_count_labels));
        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.tradeTimes)
                .label(getString(R.string.trade_times_label))
                .caption(getString(R.string.trade_times_caption))
                .spinnerData(transfers)
                .value(vehicle.getSummary().getTradeTimes() + "")
                .buildSpinnerConfig());
        String brief = vehicle.getDesc().getBrief();
        items.add(new ItemConfig.Builder()
                .key(KKCheDBHelper.VehicleColumns.briefDesc)
                .label(getString(R.string.brief_desc_label))
                .hint(getString(R.string.brief_desc_input_hint))
                .singleLine(false)
                .value(brief)
                .noMaxWidth(true)
                .buildEditTextConfig());

        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.maintenance)
                .label(getString(R.string.maintenance_label))
                .value(StringUtils.boolToStringYesNo(vehicle.getSummary().isMaintenance()))
                .buildSwitchConfig());
        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.accident)
                .label(getString(R.string.accident_label))
                .value(StringUtils.boolToStringYesNo(vehicle.getSummary().isAccident()))
                .buildSwitchConfig());

        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.registrationCertDoc)
                .label(getString(R.string.registration_cert_doc_label))
                .value(StringUtils.boolToStringYesNo(vehicle.getDocument().isRegistrationCertificate()))
                .buildSwitchConfig());
        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.purchaseTaxDoc)
                .label(getString(R.string.purchase_tax_doc_label))
                .value(StringUtils.boolToStringYesNo(vehicle.getDocument().isPurchaseTax()))
                .buildSwitchConfig());

        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.transferTicketDoc)
                .label(getString(R.string.transfer_ticket_doc_label))
                .value(StringUtils.boolToStringYesNo(vehicle.getDocument().isTransferTicket()))
                .buildSwitchConfig());

        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.maintenanceManualDoc)
                .label(getString(R.string.maintenance_manual_doc_label))
                .value(StringUtils.boolToStringYesNo(vehicle.getDocument().isMaintenanceManual()))
                .buildSwitchConfig());

        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.carTaxDoc)
                .label(getString(R.string.car_tax_doc_label))
                .value(StringUtils.boolToStringYesNo(vehicle.getDocument().isCarTax()))
                .buildSwitchConfig());

//        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.roadMaintenanceDoc)
//                .label(getString(R.string.road_maintenance_doc_label))
//                .value(StringUtils.boolToStringYesNo(vehicle.getDocument().isRoadMaintenance()))
//                .buildSwitchConfig());

        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.instructionsDoc)
                .label(getString(R.string.instruction_doc_label))
                .value(StringUtils.boolToStringYesNo(vehicle.getDocument().isInstructions()))
                .buildSwitchConfig());

        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.consignment)
                .label(getString(R.string.consignment_label))
                .value(StringUtils.boolToStringYesNo(vehicle.getSummary().isConsignment()))
                .buildSwitchConfig());


//        items.add(new ItemConfig.Builder().key(KKCheDBHelper.VehicleColumns.propertyDoc)
//                .label(getString(R.string.property_doc_label))
//                .value(StringUtils.boolToStringYesNo(vehicle.getDocument().isProperty()))
//                .buildSwitchConfig());
        return items;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        ItemConfig config = (ItemConfig) adapterView.getItemAtPosition(i);
        itemKey = config.getKey();
        if (KKCheDBHelper.VehicleColumns.drivingLicensePicture.equals(itemKey)) {
            Intent intent = new Intent(this, GalleryChooserActivity.class);
            intent.putExtra("limitation", 1);
            startActivityForResult(intent, 101);
        }
        if (config instanceof ItemDatePickerConfig) {
            if (datePickerFragment == null) {
                datePickerFragment = new DatePickerFragment();
                datePickerFragment.setOnDateSelectedListener(this);
            }
            if (KKCheDBHelper.VehicleColumns.commercialInsuranceExpireDate.equals(itemKey)) {
//                datePickerFragment.setMaxDate(DateUtils.getInsuranceLimitation());
//                datePickerFragment.setMinDate(DateUtils.nowMillis());
            }
            if (KKCheDBHelper.VehicleColumns.alcInsuranceExpireDate.equals(itemKey)) {
//                datePickerFragment.setMaxDate(DateUtils.getInsuranceLimitation());
//                datePickerFragment.setMinDate(DateUtils.nowMillis());
            }
            datePickerFragment.show(getSupportFragmentManager(), "datePicker");
            String value = config.getValue();
            if (TextUtils.isEmpty(value)) {
                value = DateUtils.formatISO8601(DateUtils.formatToYearMonthDay(new DateTime().toString()));
            }
            if (StringUtils.hasText(value)) {
                int[] d = DateUtils.formatToArray(value);
                if (d != null) {
                    datePickerFragment.updateDate(d[0], d[1], d[2]);
                }
            }
        }
    }

    @Override
    public void onDateSelected(DatePicker view, int year, int month, int day) {
        if (itemKey.equals(KKCheDBHelper.VehicleColumns.manufactureDate)) {
            adapter.updateValueForKey(itemKey, DateUtils.formatISO8601(year, ++month, day));
            return;
        }
        if (new DateTime(year, month + 1, day, 0, 0, 0, 0).getMillis() < new DateTime().getMillis()) {
            new android.app.AlertDialog.Builder(VehicleEditorStep3Activity.this)
                    .setTitle("温馨提示")
                    .setMessage("选择的时间不能小于当前月份")
                    .setPositiveButton("确定", null).create().show();
            return;
        }
        adapter.updateValueForKey(itemKey, DateUtils.formatISO8601(year, ++month, day));
        itemKey = "";
    }

    @Override
    public void onDateClean() {
        adapter.updateValueForKey(itemKey, null);
        itemKey = "";
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_vehicle_step1, menu);
        MenuItem item = menu.findItem(R.id.next);
        item.setIcon(new DrawableAwesome.DrawableAwesomeBuilder(this, R.string.fa_check).build());
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        dbHelper.close();
        super.onDestroy();
    }

    private void back() {
        setResult(RESULT_CANCELED);
        finish();    //finish当前activity
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }
//
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                back();
                return true;
            case R.id.next:
//                Vehicle vehicle = dbHelper.findVehicleByRowId(rowId);
                List<ItemConfig> items = adapter.getData();
                boolean hasError = false;
                for (ItemConfig itemConfig : items) {
                    String key = itemConfig.getKey();
                    String value = itemConfig.getValue();
                    //StringUtils.hasText(value)早期判断，加入清除功能后改变
                    if (key.equals(KKCheDBHelper.VehicleColumns.drivingLicensePicture)) {
                        if (!StringUtils.hasText(value)) {

                        } else {
                            vehicle.getSummary().setDrivingLicensePicture(value);
                        }
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.licenseNumber)) {
                        vehicle.getSummary().setLicenseNumber(value);
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.commercialInsuranceExpireDate)) {
                        vehicle.getVehicleDate().setCommercialInsuranceExpireDate(value);
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.alcInsuranceExpireDate)) {
                        vehicle.getVehicleDate().setCompulsoryInsuranceExpireDate(value);
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.manufactureDate)) {
                        if (StringUtils.hasText(value)) {
                            vehicle.getVehicleDate().setManufactureDate(value);
                        } else {
                            vehicle.getVehicleDate().setManufactureDate(vehicle.getVehicleDate().getRegistrationDate());
                        }
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.bidPrice)) {
                        if (StringUtils.hasText(value) && !StringUtils.isValidPrice(value)) {
                            hasError = hasError || true;
                            itemConfig.setErrorMessage(getString(R.string.error_msg_invalid_price));
                        } else {
                            vehicle.getPrice().setBidPriceByTenGrand(value);
                            itemConfig.clearErrorMessage();
                        }
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.briefDesc)) {
                        if (StringUtils.hasText(value) && value.length() > 15) {
                            hasError = hasError || true;
                            itemConfig.setErrorMessage(getString(R.string.error_msg_brief_desc));
                        } else if (!TextUtils.isEmpty(StringUtils.isMobileMode(this, value))) {
                            hasError = hasError || true;
                            new AlertDialog.Builder(VehicleEditorStep3Activity.this)
                                    .setTitle("温馨提示")
                                    .setCancelable(false)
                                    .setMessage("你输入的内容中包含联系方式:" + StringUtils.isMobileMode(this, value) + "请删除后再继续")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).create().show();
                        } else {
                            vehicle.getDesc().setBrief(value);
                            itemConfig.clearErrorMessage();
                        }
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.tradeTimes)) {
                        vehicle.getSummary().setTradeTimes(Integer.parseInt(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.maintenance)) {
                        vehicle.getSummary().setMaintenance(StringUtils.yesNoToBool(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.accident)) {
                        vehicle.getSummary().setAccident(StringUtils.yesNoToBool(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.carTaxDoc)) {
                        vehicle.getDocument().setCarTax(StringUtils.yesNoToBool(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.instructionsDoc)) {
                        vehicle.getDocument().setInstructions(StringUtils.yesNoToBool(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.maintenanceManualDoc)) {
                        vehicle.getDocument().setMaintenanceManual(StringUtils.yesNoToBool(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.propertyDoc)) {
                        vehicle.getDocument().setProperty(StringUtils.yesNoToBool(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.purchaseTaxDoc)) {
                        vehicle.getDocument().setPurchaseTax(StringUtils.yesNoToBool(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.registrationCertDoc)) {
                        vehicle.getDocument().setRegistrationCertificate(StringUtils.yesNoToBool(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.roadMaintenanceDoc)) {
                        vehicle.getDocument().setRoadMaintenance(StringUtils.yesNoToBool(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.transferTicketDoc)) {
                        vehicle.getDocument().setTransferTicket(StringUtils.yesNoToBool(value));
                    }
                    if (key.equals(KKCheDBHelper.VehicleColumns.consignment)) {
                        vehicle.getSummary().setConsignment(StringUtils.yesNoToBool(value));
                    }

                }
                if (hasError) {
                    adapter.refresh(items);
                    return true;
                }
                dbHelper.updateVehicle(rowId, vehicle);

                if (StringUtils.hasText(vehicle.getId())) {
                    updateVehicle(vehicle);
                } else {
//                    PreferencesUtils.setAddVehicle(getApplication(), true);
                    nextStep(0);
                }

                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateVehicle(Vehicle vehicle) {
        final ProgressDialog dialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
        dialog.setMessage(
                getString(R.string.updating));
        dialog.show();

        vehicle.washDataForDearServer();
        getBSSService().updateVehicle(vehicle, new Callback<Vehicle>() {
            @Override
            public void success(Vehicle result, Response response) {
                dialog.dismiss();
                dbHelper.removeVehicle(rowId);
                Toast.makeText(VehicleEditorStep3Activity.this, getString(R.string.update_success), Toast.LENGTH_LONG).show();
                nextStep(1);
            }

            @Override
            public void failure(RetrofitError error) {
                dialog.dismiss();
                Guard.handleError(VehicleEditorStep3Activity.this, error);
            }
        });
    }

    private void nextStep(int targetPosition) {
//        String target = getIntent().getStringExtra("target");
//
//        if (!StringUtils.hasText(target)) {
//            Intent intent = new Intent(getApplication(), MainActivity.class);
//            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.putExtra("pagerCurrentItem", targetPosition);
//            startActivity(intent);
//        } else if ("distributionLog".equalsIgnoreCase(target)) {
//
//        }
        Intent data = new Intent();
        setResult(RESULT_OK, data);
        finish();
        overridePendingTransition(R.anim.abc_slide_in_bottom, R.anim.slide_out_bottom);
    }

//    private Uri target;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 101 && resultCode == RESULT_OK) {
            ArrayList<CharSequence> paths = data.getCharSequenceArrayListExtra("paths");
            if (paths != null && paths.size() == 1) {
                CharSequence path = paths.get(0);
                String pathStr = path.toString();
                Uri source = Uri.fromFile(new File(pathStr));
                String sourceNew = pathStr.substring(0, pathStr.lastIndexOf(".")) + "_new" + pathStr.substring(pathStr.lastIndexOf("."), pathStr.length());
//                target = Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_IMAGE));
                if (ImageUtils.cropImage(source.getPath(), sourceNew, 800, 600, false)) {
                    uploadPhoto(new File(sourceNew));
                } else {
                    Toast.makeText(this, "图片处理错误!", Toast.LENGTH_LONG).show();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResumeFragments() {
        tag = 0;
        super.onResumeFragments();
    }

    private void uploadPhoto(final File photoFile) {
        final ProgressDialog dialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
        dialog.setMessage(
                getString(R.string.uploading));
        dialog.show();
        TypedFile file = new TypedFile("image/jpeg", photoFile);
        getBSSService().uploadAvatar(file, "origin", new Callback<Map<String, String>>() {
            @Override
            public void success(Map<String, String> map, Response response) {
                dialog.dismiss();
                String path = map.get("result");
                adapter.updateValueForKey(KKCheDBHelper.VehicleColumns.drivingLicensePicture, path);
                try {
                    photoFile.delete();
//                    target = null;
                } catch (Exception e) {
//                    MobclickAgent.reportError(getContext(), e);
                }
            }

            @Override
            public void failure(final RetrofitError error) {
                dialog.dismiss();
                Guard.handleError(VehicleEditorStep3Activity.this, error);
            }
        });
    }
}
